package com.shop.shoppingmall.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.shoppingmall.config.SysLoginModel;
import com.shop.shoppingmall.dao.ShUserDao;
import com.shop.shoppingmall.entity.ShUser;
import com.shop.shoppingmall.service.ShUserService;
import com.shop.shoppingmall.util.*;
import com.shop.shoppingmall.util.api.vo.Result;
import com.shop.shoppingmall.util.encryption.EncryptedString;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacpp.presets.opencv_core;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.crypto.MacSpi;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户表(ShUser)表控制层
 *
 * @author makejava
 * @since 2020-09-05 15:25:57
 */
@RestController
@RequestMapping("shUser")
@CrossOrigin
@Slf4j
public class ShUserController {
    /**
     * 服务对象
     */
    @Resource
    private ShUserService shUserService;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private ShUserDao shUserDao;

    private static final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";

    /**
     * 用户注册
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("regist")
    public Result regist(@RequestBody JSONObject jsonObject) {
        return shUserService.regist(jsonObject);

    }

    /**
     * 用户登录
     *
     * @param map
     * @return
     */
    @PostMapping("userLogin")
    public Result userLogin(@RequestBody Map map) {
        return shUserService.userLogin(map);

    }

    /**
     * 获取加密字符串
     *
     * @return
     */
    @GetMapping(value = "/getEncryptedString")
    public Result<Map<String, String>> getEncryptedString() {
        Result<Map<String, String>> result = new Result<Map<String, String>>();
        Map<String, String> map = new HashMap<String, String>();
        map.put("key", EncryptedString.key);
        map.put("iv", EncryptedString.iv);
        result.setResult(map);
        return result;
    }

    /**
     * 后台生成图形验证码 ：有效
     *
     * @param response
     * @param key
     */
    @ApiOperation("获取验证码")
    @GetMapping(value = "/randomImage/{key}")
    public Result<String> randomImage(HttpServletResponse response, @PathVariable String key) {
        Result<String> res = new Result<String>();
        try {
            String code = RandomUtil.randomString(BASE_CHECK_CODES, 4);
            String lowerCaseCode = code.toLowerCase();
            String realKey = MD5Util.MD5Encode(lowerCaseCode + key, "utf-8");
            redisUtil.set(realKey, lowerCaseCode, 60);
            String base64 = RandImageUtil.generate(code);
            res.setSuccess(true);
            res.setResult(base64);
        } catch (Exception e) {
            res.error500("获取验证码出错" + e.getMessage());
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 图形验证码
     *
     * @param sysLoginModel
     * @return
     */
    @RequestMapping(value = "/checkCaptcha", method = RequestMethod.POST)
    public Result<?> checkCaptcha(@RequestBody SysLoginModel sysLoginModel) {
        String captcha = sysLoginModel.getCaptcha();
        String checkKey = sysLoginModel.getCheckKey();
        if (captcha == null) {
            return Result.error("验证码无效");
        }
        String lowerCaseCaptcha = captcha.toLowerCase();
        String realKey = MD5Util.MD5Encode(lowerCaseCaptcha + checkKey, "utf-8");
        Object checkCode = redisUtil.get(realKey);
        if (checkCode == null || !checkCode.equals(lowerCaseCaptcha)) {
            return Result.error("验证码错误");
        }
        return Result.ok();
    }

    /**
     * 冻结状态的操作
     *
     * @param
     * @return
     */
    @PostMapping("/updateStatus")
    public Result updateStatus(@RequestBody Map map) {
        String id = (String) map.get("id");
        String status = (String) map.get("status");
        return shUserService.updateStatus(id, status);
    }

    /**
     * 对该用户进行假删除的操作
     *
     * @param
     * @return
     */
    @PostMapping("/deleteUserDelFlag")
    public Result deleteUserDelFlag(@RequestBody Map map) {
        String id = (String) map.get("id");
        String delFlag = (String) map.get("delFlag");
        return shUserService.deleteUserDelFlag(id, delFlag);
    }

    /**
     * 根据实体条件对所有用户进行查询
     *
     * @param map
     * @return
     */
    @PostMapping("/selectUserAll")
    public Result selectUserAll(@RequestBody Map map) {
        return shUserService.selectUserAll(map);
    }

    /**
     * 获取短信验证码
     *
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/sms")
    public Result<String> sms(@RequestBody JSONObject jsonObject) {
        String loginName = jsonObject.get("loginName").toString();
        //手机号模式 忘记密码: "2"  注册模式: "1"
        String smsmode = jsonObject.get("smsmode").toString();

        return shUserService.smsLogin(loginName, smsmode);
    }

    /**
     * 重置密码
     *
     * @param
     * @param
     * @return
     */
    @PostMapping("deleteByUserId")
    public Result deleteByUserId(@RequestBody Map map) {
        String loginName = (String) map.get("loginName");
        String captcha = (String) map.get("captcha");
        String passWord = (String) map.get("passWord");
        ShUser shUser = shUserDao.selectLoginName(loginName);
        if (shUser == null) {
            return Result.error("该账号未注册,请先注册");
        }
        return shUserService.changePassword(shUser,captcha, passWord);
    }

    /**
     * 修改密码
     *
     * @param json
     * @param request
     * @return
     */
    @PostMapping(value = "/updatePassword")
    public Result changPassword(@RequestBody JSONObject json, HttpServletRequest request) {
        String oldpassword = json.getString("oldpassword");
        String password = json.getString("password");
        String confirmpassword = json.getString("confirmpassword");
        String name = JwtUtil.getUserNameByToken(request);
        ShUser shUser = shUserDao.selectLoginName(name);
        if (shUser == null || name == null) {
            return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
        }
        return shUserService.resetPassword(shUser.getLoginName(), oldpassword, password, confirmpassword);
    }

    /**
     * 查询用户个人信息
     * @param request
     * @return
     */
    @GetMapping("/selectShUserByLoginName")
    public Result selectShUserByLoginName(HttpServletRequest request){
        return shUserService.selectShUserByLoginName(request);
    }

    /**
     * 修改用户信息
     * @param request
     * @param jsonObject
     * @return
     */
    @PostMapping("/updateUser")
    public Result updateUser(HttpServletRequest request,@RequestBody JSONObject jsonObject){
        ShUser shUser = JSON.parseObject(jsonObject.toJSONString(), ShUser.class);
        String name = JwtUtil.getUserNameByToken(request);
        ShUser shUser1 = shUserDao.selectLoginName(name);
        if (shUser1 == null || name == null) {
            return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
        }
        shUser.setId(shUser1.getId());
        return shUserService.updateUser(shUser);
    }

    /**
     * 用户修改手机号
     * @param request
     * @param
     * @return
     */
    @PostMapping("/updateUserNameMobile")
    public Result updateUserNameMobile(HttpServletRequest request,@RequestBody Map map){
        String loginName = (String) map.get("loginName");
        String captcha = (String) map.get("captcha");
        return shUserService.updateUserNameMobile(request,loginName,captcha);
    }

    /**
     * 查询该用户所有信息
     * @param request
     * @return
     */
    @GetMapping("/selectShUserAll")
    public Result selectShUserAll(HttpServletRequest request){
        return shUserService.selectShUserAll(request);
    }

    /**
     * 查询用户个人邀请码，及邀请用户的信息
     * @param request
     * @return
     */
    @GetMapping("/selectUserBySuperiorCode")
    public Result selectUserBySuperiorCode(HttpServletRequest request){
        return shUserService.selectUserBySuperiorCode(request);
    }
}
